﻿using UnityEngine;

public class RotationUtility
{
    public static void RotationToTarget(Transform target, Transform source, float rotationZOffset, float smoothSpeed)
    {
        // 计算指向敌人的方向向量
        Vector2 direction = ((Vector2)target.position - (Vector2)source.position).normalized;

        // 计算目标角度（包含Z轴偏移量）
        float targetAngle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        targetAngle += rotationZOffset;

        // 标准化角度到[-180, 180]范围，确保误差计算准确（解决360度循环问题）
        float normalizedTargetAngle = NormalizeAngle(targetAngle);
        float normalizedCurrentAngle = NormalizeAngle(source.eulerAngles.z);

        // 计算最短路径的角度误差（范围：[-180, 180]）
        float angleError = Mathf.DeltaAngle(normalizedCurrentAngle, normalizedTargetAngle);

        // 误差小于1度时，直接锁定目标角度，不再插值
        if (Mathf.Abs(angleError) <= 1f)
        {
            source.rotation = Quaternion.Euler(0, 0, targetAngle);
            return;
        }

        // 误差较大时，平滑插值转向
        float smoothedAngle = Mathf.LerpAngle(source.eulerAngles.z, targetAngle, smoothSpeed * Time.deltaTime);
        source.rotation = Quaternion.Euler(0, 0, smoothedAngle);
    }

    /// <summary>
    /// 将角度标准化到[-180, 180]范围，避免角度计算错误
    /// </summary>
    private static float NormalizeAngle(float angle)
    {
        while (angle > 180) angle -= 360;
        while (angle < -180) angle += 360;
        return angle;
    }
}